package sharedServlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import sessionMenegment.SessionMgr;

import controller.Controller;

@SuppressWarnings("serial")
public class LogIn extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("log in =)");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		SessionMgr sessionMgr = SessionMgr.getInst();
		System.out.println("log in");
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		String type = req.getParameter("type");
		String remember = req.getParameter("remember");
		System.out.println(userName);
		int logInStatus;
		
		if (type.equals("customer")){
			logInStatus = Controller.getInstance().ClientlogIn(userName, password);
		}
		else{
			logInStatus = Controller.getInstance().BizlogIn(userName, password);
		}
		
		switch(logInStatus)
		{
		case 0:
			req.getSession().removeAttribute("error");
			if (type.equals("customer"))
			{
				req.getSession().setAttribute("userNameClient", userName);
				sessionMgr.registerUser(req.getSession(), userName,"client");
				System.out.println("client log in");
				if(remember!=null)
					sessionMgr.addCoockie(resp, userName, password, "userNameClient");
				resp.sendRedirect("allClientOrders.jsp");
			}
			else //business
			{
				req.getSession().setAttribute("userNameBusiness", userName);
				
				sessionMgr.registerUser(req.getSession(), userName,"biz");
				if(remember!=null)
					sessionMgr.addCoockie(resp, userName, password, "userNameBusiness");
				resp.sendRedirect("allOrders.jsp");
				System.out.println("business log in");
			}
			
			break;
		case 2:
			req.getSession().setAttribute("error","wrong user Name / password"); //"wrongPassword"
			System.out.println("wrongPassword");
			resp.sendRedirect("home.jsp");
			break;
		default:
			req.getSession().setAttribute("error","wrong user Name / password"); //"wrongUser"
			System.out.println("wrongUser");
			resp.sendRedirect("home.jsp");
			break;
		
		}
		
		System.out.println("log in post   "+type);
		//resp.setStatus(200)
		

	}
	
}
